<template>
  <div>
    <ZWDrawer ref="zwRef" @submit="save" @close="close" @cancel="cancel">
      <div class="contents">
        <el-form :model="form" label-width="auto">
          <el-form-item label="线索公海" required>
            <el-select v-model="form.seas_id" placeholder="请选择线索公海"
              ><el-option v-for="(item, index) in seaids" :value="item.id" :label="item.name">{{ item.name }}</el-option></el-select
            >
          </el-form-item>
          <el-form-item :label="item.attr_name" v-for="(item, index) in getData" :required="item.is_required == 2">
            <el-input v-model="item.current_val" :placeholder="'请输入'+item.attr_name" v-if="item.attr_type == 'textbox'" @blur="valiateid(index, item.is_required)" />
            <el-input v-model="item.current_val" :placeholder="'请输入'+item.attr_name" v-if="item.attr_type == 'mobile'" indeterminate @blur="valiate(index, item.is_required)" />
            <el-checkbox-group v-model="item.current_val" v-if="item.attr_type == 'muti_select'">
              <el-checkbox v-for="items in item.attr_val" :label="items.key">{{ items.val }}</el-checkbox>
            </el-checkbox-group>
            <el-select v-model="item.current_val" v-if="item.attr_type == 'select'" :placeholder="'请选择'+item.attr_name">
              <el-option v-for="items in item.attr_val" :value="items.key" :label="items.val">{{ items.val }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="线索等级" required>
            <el-select v-model="form.clue_grade_id" placeholder="请选择线索等级"
              ><el-option v-for="(item, index) in levelid" :value="item.id" :label="item.name">{{ item.name }}</el-option></el-select
            > </el-form-item
          ><el-form-item label="线索来源">
            <el-select v-model="form.clue_source_id" placeholder="请选择线索来源"
              ><el-option v-for="(item, index) in sourceid" :value="item.id" :label="item.name">{{ item.name }}</el-option></el-select
            >
          </el-form-item>
          <el-form-item label="归属员工">
            <el-tag v-for="item in creators" :key="item.name" class="staffs_item" closable @close="handleClose(item)" :type="item.id">
              {{ item.name }}
            </el-tag>
            <div>
              <el-button @click="openDepart">选择员工</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </ZWDrawer>
    <ZWDepart ref="DepartRef" @submit="getDepart" type="1"/>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import ZWDrawer from '@/components/ZWDrawer.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import { personClub, getClubSource, getClubLevel, seaList, savepersonClub } from '@/api/customer/clubManage/commonSea'
  import { getSetionId } from '@/utils/utils'
  const emit = defineEmits(['close', 'submit'])
  const props = defineProps(['open', 'seas_id', 'isEdit', 'rowid'])
  const zwRef = ref(null)
  const DepartRef = ref(null)
  const creators = ref([])
  let form = reactive({
    seas_id: '',
    clue_grade_id: '', //线索等级id
    clue_source_id: '', //线索来源id
    belong_work_user_id: ''
  })
  const getData = ref([])
  const getDetail = () => {
    if (props.isEdit) {
      personClub({ clue_id: props.rowid }).then((res) => {
        for (let key in res) {
          if (key != 'custom_attr') {
            form[key] = res[key]
          }
        }
        getData.value = res.custom_attr
        getData.value.forEach((item) => {
          if (item.attr_type == 'muti_select' && !item.current_val) {
            item.current_val = []
          }
        })
      })
    } else {
      personClub().then((res) => {
        getData.value = res.custom_attr
        operateParam()
      })
    }
  }
  const seaids = ref([]) //公海列表
  const levelid = ref([]) //线索等级列表
  const sourceid = ref([]) //线索来源
  //获取公海列表
  const getSeaList = () => {
    seaids.value = []
    seaList({ page: 1, page_size: 99 }).then((res: any) => {
      seaids.value = res.data
    })
  }
  //获取线索等级
  const getLevelList = () => {
    levelid.value = []
    getClubLevel({ page: 1, page_size: 99 }).then((res: any) => {
      res.data.forEach((item) => {
        if (item.status == 1) {
          //筛选已开启的线索等级
          levelid.value.push(item)
        }
      })
    })
  }
  //获取线索来源
  const getSourceList = () => {
    sourceid.value = []
    getClubSource({ page: 1, page_size: 99 }).then((res: any) => {
      res.data.forEach((item) => {
        if (item.status == 1) {
          //筛选开始的线索来源
          sourceid.value.push(item)
        }
      })
    })
  }
  const valiate = (index: any, required?: any) => {
    let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (!rex.test(getData.value[index].current_val)) {
      ElMessage.warning('请输入合法的手机号')
      return false
    } else {
      return true
    }
  }
  const valiateid = (index: any, required: any) => {
    let rex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{16,}$/
    if (getData.value[index].attr_name != '姓名' && required == 2) {
      if (!rex.test(getData.value[index].current_val)) {
        ElMessage.warning(getData.value[index].attr_name + '必须包含数字字母并且长度不能小于16位')
        return false
      } else {
        return true
      }
    } else {
      return true
    }
  }
  const save = () => {
    const data = getData.value
    try {
      data.forEach((item, index) => {
        if (!item.current_val && item.is_required == 2 && item.attr_type != 'muti_select') {
          ElMessage.warning(item.attr_name + '不能为空')
          throw new Error()
        } else if (item.attr_type == 'muti_select' && item.is_required == 2 && !item.current_val.length) {
          ElMessage.warning(item.attr_name + '不能为空')
          throw new Error()
        }
      })
    } catch (e) {
      return
    }
    if (!form.clue_grade_id) {
      ElMessage.warning('线索等级不能为空')
      return
    }
    try {
      data.forEach((items, indexs) => {
        if (items.is_required == 2 && items.attr_type == 'mobile') {
          let flag = valiate(indexs)
          if (!flag) {
            throw new Error()
          }
        } else if (items.is_required == 2 && items.attr_name != '姓名') {
          let flag = valiateid(indexs, 2)
          if (!flag) {
            throw new Error()
          }
        }
      })
    } catch (e) {
      return
    }
    data.forEach((item) => {
      delete item.attr_val
      delete item.is_required
      delete item.system_code
    })
    if (props.isEdit) {
      savepersonClub({ ...form, custom_attr: data, clue_id: props.rowid }).then((res) => {
        emit('submit')
        ElMessage.success('编辑成功')
        zwRef.value.drawer = false
      })
    } else {
      savepersonClub({ ...form, custom_attr: data }).then((res) => {
        emit('submit')
        ElMessage.success('保存成功')
        zwRef.value.drawer = false
      })
    }
  }
  const cancel = () => {
    for (let key in form) {
      if (key != 'custom_attr' && key != 'seas_id') {
        form[key] = ''
      }
      operateParam()
    }
  }
  //数据
  const operateParam = () => {
    getData.value.forEach((item) => {
      if (item.attr_type == 'muti_select') {
        item.current_val = []
      } else {
        item.current_val = ''
      }
    })
  }
  const openDepart = () => {
    // 记录是那个员工弹框
    DepartRef.value.multiple = false
    DepartRef.value.departVisble = true
    DepartRef.value.selectedMember = [...creators.value]
  }
  // 获取部门成员
  const getDepart = (res: any) => {
    creators.value = res
    form.belong_work_user_id = getSetionId('id', creators.value).length ? getSetionId('id', creators.value)[0] : ''
    DepartRef.value.departVisble = false
  }
  // 员工移除
  const handleClose = (data: any) => {
    creators.value = []
    form.belong_work_user_id = ''
    DepartRef.value.removeItem(data)
  }
  const close = () => {
    emit('close')
  }
  watch(
    () => props.open,
    (val) => {
      if (val) {
        form.seas_id = props.seas_id
        form.clue_grade_id = ''
        form.clue_source_id = ''
        creators.value = []
        zwRef.value.resetMsg = '重置'
        zwRef.value.drawerMsg = '保存'
        zwRef.value.isResetShow = true
        if (props.isEdit) {
          zwRef.value.title = '编辑线索'
        } else {
          zwRef.value.title = '新增线索'
        }
        getDetail()
        getSourceList()
        getLevelList()
        getSeaList()
        zwRef.value.drawer = true
        zwRef.value.width = '600px'
      }
    }
  )
</script>
<style scoped lang="scss">
  .contents {
    padding: 16px 0;
  }
</style>
